package com.woniuxy.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.response.CustomPage;
import com.woniuxy.response.ResponseResult;
import com.woniuxy.system.demol.entity.*;
import com.woniuxy.system.demol.vo.SpeUserVo;
import com.woniuxy.system.demol.vo.UserVo;
import com.woniuxy.system.mapper.UserMapper;
import com.woniuxy.system.service.PermsService;
import com.woniuxy.system.service.SystemUserUpdateService;
import com.woniuxy.system.service.UserRoleService;
import com.woniuxy.system.service.UserService;

import com.woniuxy.util.CheckTokenUtil;
import org.apache.http.HttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private SystemUserUpdateService systemUserUpdateService;
    @Resource
    private UserRoleService userRoleService;

    @GetMapping("/password/{account}/{password}")
    public ResponseResult<String> password(@PathVariable("account")String account,@PathVariable("password")String password ){


        User user = new User().setAccount(account).setState("0");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        List<User> users = userService.list(queryWrapper);
        if (Objects.isNull(users)||users.size()==0){
            return new ResponseResult<>(500,"error",null);
        }else {
            //BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
          //  String encode = encoder.encode(password);
          Boolean a=  userService.fundPassword(password,account);
          if (a){
              return new ResponseResult<>(ResponseResult.SUCCESS,"success",null);
          }else {
              return new ResponseResult<>(501,"error",null);
          }
        }

    }



    //无条件查询所有的账户
    @GetMapping("/findall2/{currentPage}/{pageSize}")
    public ResponseResult<Map<String, Object>> findall2(@PathVariable("currentPage")Integer currentPage,@PathVariable("pageSize")Integer pageSize ){
        int i = userService.pageListCount();
        int offset =0;
        if (currentPage==1){

        }else {
            offset = (currentPage-1)*pageSize ;
        }

        Map<String, Object> all2 = userService.findAll2(offset, pageSize);
       // System.out.println(all2);


        return new ResponseResult<>(ResponseResult.SUCCESS,"success",all2);
    }

    //增加用户信息

    @PreAuthorize("hasAnyAuthority('sale:agreePack','depot:agreeIn','depot:agreeOut','buy:agreeBuy','top:adduser','com:openClient','goods:salePrice','finance:lockaccout')")
    @PostMapping("/addUser")
    public ResponseResult<Boolean> addUser(@RequestBody UserVo userVo,HttpServletRequest request){
        System.out.println(userVo);
        String aid = request.getHeader("access_token");
        Map<String, Object> cUser = CheckTokenUtil.getUser(aid);
        Integer i = (Integer) cUser.get("uid");
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        Date date = new Date();
        String format = formatter.format(date);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(userVo.getPassword());
        User user = new User().setAccount(userVo.getAccount())
                .setCellphone(userVo.getCellphone()).setAid(i)
                .setSid(userVo.getSid()).setTime(format)
                .setState("0").setPassword(encode);

        //增加用户信息
        Boolean save = userService.save(user);
        if (save){
            userVo.setTime(format).setAid(i).setState("0").setPassword(encode).setId(user.getId());
            //用户基本信息增加成功，则将信息记录到用户角色表
         Boolean a=   userService.addUser(userVo);
         if (a){
             return new ResponseResult<>(ResponseResult.SUCCESS,"success",save);
         }

        }
        return new ResponseResult<>(ResponseResult.SYSTEM_ERROR,"error",null);
    }



    //修改员工的信息
    @PreAuthorize("hasAnyAuthority('sale:agreePack','depot:agreeIn','depot:agreeOut','buy:agreeBuy','top:adduser','com:openClient','goods:salePrice','finance:lockaccout')")
    @PostMapping("/updateUser")
    public ResponseResult<Boolean>updateUser(@RequestBody UserVo userVo, HttpServletRequest request){
        String aid = request.getHeader("access_token");
        Map<String, Object> cUser = CheckTokenUtil.getUser(aid);
        Integer i = (Integer) cUser.get("uid");
        userVo.setAid(i);
        if (Objects.isNull(userVo.getIdentity())){
            Boolean b= userService.updateUser(userVo);
            if (b){
                return new ResponseResult<>(ResponseResult.SUCCESS,"success",b);
            }
        }else {
            Boolean b=   userService.updateUser2(userVo);
            if (b){
                return new ResponseResult<>(ResponseResult.SUCCESS,"success",b);
            }

        }
       //userVo.setAid(99);
     // Boolean b= userService.updateUser(userVo);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",false);
    }

    //停用账号

    @PreAuthorize("hasAnyAuthority('sale:agreePack','depot:agreeIn','depot:agreeOut','buy:agreeBuy','top:adduser','com:openClient','goods:salePrice','finance:lockaccout')")
    @GetMapping("/stopUser/{id}")
    public ResponseResult<Boolean> stopRole(@PathVariable("id") Integer id,HttpServletRequest request){
        String aid = request.getHeader("access_token");
        Map<String, Object> cUser = CheckTokenUtil.getUser(aid);
        Integer i = (Integer) cUser.get("uid");
        User user = new User().setAid(i).setState("1").setId(id);
        boolean b = userService.saveOrUpdate(user);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",b);
    }

    //启用账号
    @PreAuthorize("hasAnyAuthority('sale:agreePack','depot:agreeIn','depot:agreeOut','buy:agreeBuy','top:adduser','com:openClient','goods:salePrice','finance:lockaccout')")
    @GetMapping("/openUser/{id}")
    public ResponseResult<Boolean> openRole(@PathVariable("id") Integer id,HttpServletRequest request){
        String aid = request.getHeader("access_token");
        Map<String, Object> cUser = CheckTokenUtil.getUser(aid);
        Integer i = (Integer) cUser.get("uid");
        User user = new User().setAid(i).setState("0").setId(id);
        boolean b = userService.saveOrUpdate(user);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",b);
    }

    //删除账号
    @PreAuthorize("hasAnyAuthority('sale:agreePack','depot:agreeIn','depot:agreeOut','buy:agreeBuy','top:adduser','com:openClient','goods:salePrice','finance:lockaccout')")
    @GetMapping("/delUser/{uid}")
    public ResponseResult<Boolean> delRole(@PathVariable("uid") Integer uid,HttpServletRequest request){
        String aid = request.getHeader("access_token");
        Map<String, Object> cUser = CheckTokenUtil.getUser(aid);
        Integer i = (Integer) cUser.get("uid");
        User user = new User().setAid(i).setState("3").setId(uid);
        boolean b = userService.saveOrUpdate(user);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",b);
    }
    @GetMapping("/getAllUser")
    public ResponseResult<Map> getAllUser(HttpServletRequest request){
        String aid = request.getHeader("access_token");
        Map<String, Object> user = CheckTokenUtil.getUser(aid);
        Integer uid = (Integer) user.get("uid");
        String account = (String) user.get("account");
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",user);
    }

    //根据账号查找该用户的所有信息
    @GetMapping("/findUserByAccount/{account}")
    public ResponseResult<User> findUserByAccount(@PathVariable("account") String account){
        User user = userService.findall(account);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",user);
    }

    //查看所有启用的
    @GetMapping("/findStateOpen/{currentPage}/{pageSize}")
    public ResponseResult<Map<String, Object>> findStateOpen(@PathVariable("currentPage")Integer currentPage,@PathVariable("pageSize")Integer pageSize ){
        int i = userService.pageListCount();
        int offset =0;
        if (currentPage==1){
        }else {
            offset = (currentPage-1)*pageSize ;
        }
        Map<String, Object> all2 = userService.findStateOpen(offset, pageSize);
        // System.out.println(all2);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",all2);
    }

    //查看所有禁用的
    @GetMapping("/findStateClose/{currentPage}/{pageSize}")
    public ResponseResult<Map<String, Object>> findStateClose(@PathVariable("currentPage")Integer currentPage,@PathVariable("pageSize")Integer pageSize ){
        int i = userService.pageListCount();
        int offset =0;
        if (currentPage==1){
        }else {
            offset = (currentPage-1)*pageSize ;
        }
        Map<String, Object> all2 = userService.findStateClose(offset, pageSize);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",all2);
    }

    //搜索所有
    @GetMapping("/searchAll/{num}/{input}/{currentPage}/{pageSize}")
    public ResponseResult<Map<String, Object>> findStateClose(@PathVariable("num")Integer num,@PathVariable("input")String input,@PathVariable("currentPage")Integer currentPage,@PathVariable("pageSize")Integer pageSize ){
        int i = userService.pageListCount();
        int offset =0;
        if (currentPage==1){
        }else {
            offset = (currentPage-1)*pageSize ;
        }
        Map<String, Object> all2 = userService.searchAll(num,input,offset, pageSize);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",all2);
    }
    @GetMapping("/searchHistory/{account}")
    public ResponseResult<List<SystemUserUpdate>> searchHistory(@PathVariable("account")String account){
        List<SystemUserUpdate> all=  userService.searchHistory(account);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",all);
    }

    /***
     * 查找所有用户名称
     */
    @GetMapping("/findAllAccount")
    public ResponseResult<List<User>> findAllUserByAccount(){
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",userService.findAllAccount());
    }
    @GetMapping("/findManager")
    public ResponseResult<List<UserRole>> findManager(){
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rid", 1);

        List<UserRole> users = userRoleService.list(queryWrapper);
        for (int i = 0; i < users.size(); i++) {
            Integer uid = users.get(i).getUid();
            User byId = userService.getById(uid);
            if (! byId.getState().equals("0")){
                users.remove(i);
            }
        }
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",users);
    }

    @GetMapping("/findSpeUser//{currentPage}/{pageSize}/{account}")
    public ResponseResult<Map<String, Object>> findSpeUser(@PathVariable("currentPage")Integer currentPage,@PathVariable("pageSize")Integer pageSize,@PathVariable("account")String account){
        int offset =0;
        if (currentPage==1){
        }else {
            offset = (currentPage-1)*pageSize ;
        }
        Map<String, Object> all = userService.findSpeUser(offset, pageSize,account);

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",all);
    }
    @PreAuthorize("hasAnyAuthority('sale:agreePack','depot:agreeIn','depot:agreeOut','buy:agreeBuy','top:adduser','com:openClient','goods:salePrice','finance:lockaccout')")
    @GetMapping("/updateNewRoleUser/{rid}/{speUid}")
    public ResponseResult<Boolean> updateNewRoleUser(@PathVariable("rid")Integer rid,@PathVariable("speUid")Integer speUid,HttpServletRequest request){
        System.out.println("rid:"+rid+"speUid"+speUid);
        //rid是角色id speid是账号id uid是当前操作员的id
        String aid = request.getHeader("access_token");
        Map<String, Object> user = CheckTokenUtil.getUser(aid);
        Integer uid = (Integer) user.get("uid");
        Boolean c = userService.updateSpeUser(rid,speUid,uid);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",true);
    }

}
